package com.onlinelibrary.activities.main.ui.comment;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.EditText;

import androidx.databinding.BindingAdapter;
import androidx.databinding.library.baseAdapters.BR;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;

import com.google.android.material.snackbar.Snackbar;
import com.onlinelibrary.R;
import com.onlinelibrary.activities.App;
import com.onlinelibrary.activities.reply.ReplyActivity;
import com.onlinelibrary.adapter.CommentAdapter;
import com.onlinelibrary.bean.CRBean;
import com.onlinelibrary.bean.MeListBean;
import com.onlinelibrary.databinding.FragmentCommentBinding;
import com.onlinelibrary.utils.Http;
import com.onlinelibrary.view.PullingLayout;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class CommentVM extends ViewModel {
    private static final List<CRBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private static FragmentActivity requireActivity;
    @SuppressLint("StaticFieldLeak")
    private static FragmentCommentBinding binding;
    private static int count=0;
    public CommentVM() {}
    public void setBinding(FragmentCommentBinding binding, FragmentActivity requireActivity) {
        CommentVM.requireActivity=requireActivity;
        CommentVM.binding=binding;
        binding.setVariable(BR.adp,new CommentAdapter(requireActivity,data));
        binding.commentList.setOnItemLongClickListener((parent, view, position, id) -> {
            CRBean bean = data.get(position);
            if (App.sp.getString("account","").equals(bean.email)){
                AlertDialog.Builder dia=new AlertDialog.Builder(requireActivity);
                dia.setTitle("提示").setMessage("这是您的评论，确定删除吗？").setPositiveButton("删除", (dialog, which) ->
                        Http.get("comment/?type=delete_comment&name="+bean.name+"&time="+bean.time, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                refresh(null);
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refresh(null);
                            }})).setNeutralButton("关闭",null).show();
            }
            return true;
        });
        binding.commentList.setOnItemClickListener((parent, view, position, id) -> {
            App.commentName=data.get(position).name;
            App.commentTime=data.get(position).time;
            App.commentContent=data.get(position).content;
            requireActivity.startActivity(new Intent(requireActivity, ReplyActivity.class));
        });
        App.autoLoginCheck(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                requireActivity.runOnUiThread(() -> {
                    try {
                        assert response.body() != null;
                        String res = response.body().string();
                        if (res.equals("验证成功")){
                            App.getMsg(new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    try {
                                        assert response.body() != null;
                                        JSONObject jo = new JSONObject(response.body().string());
                                        App.is_staff=jo.getBoolean("is_staff");
                                        App.hasLogin=true;
                                        @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                                        edit.putString("name",jo.getString("name"));
                                        edit.apply();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        refresh(null);
    }
    public static void addComment(View v){
        if (!App.hasLogin){
            Snackbar.make(v,"请先登录",Snackbar.LENGTH_LONG).show();
            return;
        }
        AlertDialog.Builder dia=new AlertDialog.Builder(requireActivity);
        EditText view=new EditText(requireActivity);
        view.setHint("评论点什么吧...");
        dia.setTitle("评论").setView(view).setPositiveButton("评论", (dialog, which) -> {
            try {
                JSONObject jo=new JSONObject();
                jo.put("type","create_comment");
                jo.put("name",App.sp.getString("name","游客"));
                jo.put("email",App.sp.getString("account", "defaultEmail"));
                jo.put("content",view.getText().toString());
                jo.put("visible",App.is_staff);
                Http.post(jo, "comment/", new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        requireActivity.runOnUiThread(() -> {
                            refresh(null);
                            if (!App.is_staff){
                                Snackbar.make(v,"添加完成,请请等待审核",Snackbar.LENGTH_LONG).show();
                            }else {
                                Snackbar.make(v,"添加完成",Snackbar.LENGTH_LONG).show();
                            }

                        });
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).setNeutralButton("取消",null).setCancelable(false).show();

    }
    @BindingAdapter("bindPull")
    public static void bindPull(PullingLayout pullingLayout, CommentVM commentVM){
        pullingLayout.setPullDownEnabled(true);
        pullingLayout.setPullUpEnabled(true);
        pullingLayout.setOnRefreshListener(CommentVM::refresh);
        pullingLayout.setOnLoadMoreListener(pullToLoadMoreLayout -> {
            Http.get("comment/?type=get_comment&start="+count+"&end="+(count+20)+"&commentType=visible", new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    requireActivity.runOnUiThread(() -> pullToLoadMoreLayout.loadmoreFinish(1));
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    try {
                        JSONObject res = new JSONObject(response.body().string());
                        if (res.getString("data").equals("No Comment")){
                            requireActivity.runOnUiThread(() -> pullToLoadMoreLayout.loadmoreFinish(2));
                        }else {
                            JSONArray ja = res.getJSONArray("data");
                            for (int i = 0; i < ja.length(); i++){
                                JSONObject jo = ja.getJSONObject(i);
                                data.add(new CRBean(true,jo.getString("time"),jo.getString("name"),jo.getString("content"),jo.getString("email")));
                            }
                            requireActivity.runOnUiThread(() -> {
                                binding.getAdp().notifyDataSetChanged();
                                count=data.size();
                                pullToLoadMoreLayout.loadmoreFinish(0);
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        });
    }
    private static void refresh(PullingLayout pullToRefreshLayout) {
        count=0;
        data.clear();
        Http.get("comment/?type=get_comment&start=0&end=20&commentType=visible", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                requireActivity.runOnUiThread(() -> {
                    if (pullToRefreshLayout!=null)pullToRefreshLayout.refreshFinish(1);
                });
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JSONObject res = new JSONObject(response.body().string());
                    if (res.getString("data").equals("No Comment")){
                        requireActivity.runOnUiThread(() -> {
                            if (pullToRefreshLayout!=null)pullToRefreshLayout.refreshFinish(2);
                        });
                    }else {
                        JSONArray ja = res.getJSONArray("data");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                           if (jo.getBoolean("visible")){
                               data.add(new CRBean(true,jo.getString("time"),jo.getString("name"),jo.getString("content"),jo.getString("email")));
                           }
                        }
                        requireActivity.runOnUiThread(() -> {
                            binding.getAdp().notifyDataSetChanged();
                            count=data.size();
                            if (pullToRefreshLayout!=null)pullToRefreshLayout.refreshFinish(0);
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}